<!--
  * 物料分类表
  *
  * @Author:    ADog
  * @Date:      2025-09-19 19:48:13
  * @Copyright  1.0
-->
<template>
  <!---------- 查询表单form begin ----------->
  <a-form class="smart-query-form">
    <a-row class="smart-query-form-row">
      <a-form-item class="smart-query-form-item">
        <a-button type="primary" @click="queryData">
          <template #icon>
            <SearchOutlined />
          </template>
          查询
        </a-button>
      </a-form-item>
    </a-row>
  </a-form>
  <!---------- 查询表单form end ----------->

  <a-card size="small" :bordered="false" :hoverable="true">
    <!---------- 表格操作行 begin ----------->
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <a-button @click="showForm" type="primary" size="small">
          <template #icon>
            <PlusOutlined />
          </template>
          新建最高级分类
        </a-button>
      </div>
    </a-row>
    <!---------- 表格操作行 end ----------->
    <a-tree :tree-data="treeData" :loading="tableLoading"
            show-line
            :expanded-keys="expandedKeys"
    >
      <template #title="{ title, ...nodeData }">
        <div class="tree-node-wrapper">
          <span>{{ title }}</span>
          <a-button type="link" size="small" @click.stop="handleAdd(nodeData)"> 新增下级 </a-button>
          <a-button type="link" size="small" @click.stop="handleDelete(nodeData)"> 删除 </a-button>
        </div>
      </template>
    </a-tree>
    <MaterialCategoryForm ref="formRef" @reloadList="queryData" />
  </a-card>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import { SearchOutlined, PlusOutlined } from '@ant-design/icons-vue';
import { materialCategoryApi } from '/@/api/business/core/material/material-category-api';
import { smartSentry } from '/@/lib/smart-sentry';
import MaterialCategoryForm from '/@/views/business/core/material/conponents/material-category-form.vue';

const tableLoading = ref(false);

// 查询数据
const treeData = ref([]);

// 转换数据格式以适应a-tree组件
const transformToTreeFormat = (data) => {
  return data.map((item) => {
    const transformed = {
      key: item.materialCategoryId.toString(), // 转换为字符串作为key
      title: item.materialCategoryName, // 显示名称
      // 如果有子节点，递归转换
      children: item.children && item.children.length > 0 ? transformToTreeFormat(item.children) : [],
    };
    return transformed;
  });
};

const expandedKeys = ref([]);

async function queryData() {
  try {
    tableLoading.value = true;
    let queryResult = await materialCategoryApi.getTree();

    // 增加数据校验和默认值处理
    console.log('接口返回完整数据:', queryResult);

    // 确保数据存在且为数组
    const rawData = queryResult || [];
    if (!Array.isArray(rawData)) {
      console.error('接口返回的数据不是数组:', rawData);
      treeData.value = [];
      return;
    }

    // 转换数据格式
    const transformedData = transformToTreeFormat(rawData);
    treeData.value = transformedData
    console.log('转换后的数据:', treeData.value);
    // 关键：收集所有有子节点的key，赋值给expandedKeys
    expandedKeys.value = collectExpandedKeys(transformedData);
    console.log('需要展开的节点key:', expandedKeys.value);
  } catch (e) {
    smartSentry.captureError(e);
    // 出错时重置数据
    treeData.value = [];
  } finally {
    tableLoading.value = false;
  }
}


// 2. 收集所有“有子节点的节点key”
const collectExpandedKeys = (nodes) => {
  const keys = [];
  const traverse = (nodeList) => {
    nodeList.forEach(node => {
      // 若节点有子节点（children非空），则需要展开
      if (node.children && node.children.length > 0) {
        // 将该节点的key加入到keys数组中
        keys.push(node.key);
        // 递归处理子节点（子节点若有后代也需展开）
        traverse(node.children);
      }
    });
  };
  traverse(nodes);
  return keys;
};

onMounted(queryData);

// ---------------------------- 添加/修改 ----------------------------
const formRef = ref();

function showForm(data) {
  formRef.value.show(data);
}


// 新增下级
function handleAdd(nodeData) {
  console.log(nodeData.data);
  // 拿到父节点的ID即可
  const parentId = nodeData.data.key;
  console.log(parentId);
  // 将父级ID封装成对象
  const parentIdObj = {
    parentId: parentId,
  };
  formRef.value.show(parentIdObj);
}
</script>
